﻿
namespace KlearTweet.Client.DataPresentation
{
    public partial class TweetView
    {
        public TweetController Controller; // TODO: Find a better solution
        private Model.Tweet _entity;

        public TweetView()
        {
            InitializeComponent();
        }

        public Model.Tweet Entity
        {
            get { return _entity; }
            set
            {
                if (value == null)
                    throw new System.ArgumentNullException("value");
                _entity = value;
                Refresh();
            }
        }

        private void Refresh()
        {
            ProfileImageUrl.Source = new System.Windows.Media.Imaging.BitmapImage(new System.Uri(Entity.ProfileImageUrl));

            Text.Clear();

            InsertLink("from:" + Entity.FromUserScreenName, Entity.FromUserScreenName, "from:" + Entity.FromUserScreenName, true);

            Text.Add(" ");
            InsertStatusText();


            Text.AddNewLine();
            InsertLink("http://twitter.com/" + Entity.FromUserScreenName + "/status/" + Entity.Id,
                       Entity.CreatedDate.ToShortDateString() + " " + Entity.CreatedDate.ToShortTimeString());

            if (!string.IsNullOrEmpty(Entity.ToUserScreenName))
            {
                Text.Add("    in reply to @");
                InsertLink("from:" + Entity.ToUserScreenName, Entity.ToUserScreenName);
            }

            Text.Add("    ");
            var copyBtn = new System.Windows.Controls.Button { Content = "Copy" };
            copyBtn.Click += (s, e) => Text.ClipboardCopyAll();
            Text.Add(copyBtn);
        }

        private void InsertLink(string searchText)
        {
            InsertLink(searchText, searchText);
        }

        private void InsertLink(string searchText, string text)
        {
            InsertLink(searchText, text, searchText);
        }

        private void InsertLink(string searchText, string text, string tooltip)
        {
            InsertLink(searchText, text, tooltip, false);
        }

        private void InsertLink(string searchText, string text, string tooltip, bool bold)
        {
            var ctrl = Controller.TabController.GetLinkFor(searchText);
            Text.Add(ctrl);

            ctrl.Content = text;
            ctrl.FontSize = 12;
            ctrl.Padding = new System.Windows.Thickness(0);
            ctrl.Foreground = new System.Windows.Media.SolidColorBrush { Color = System.Windows.Media.Color.FromArgb(255, 45, 105, 159/*115, 169, 216*/) };
            if (bold)
                ctrl.FontWeight = System.Windows.FontWeights.Bold;
            System.Windows.Controls.ToolTipService.SetToolTip(ctrl, tooltip);
        }

        private void InsertStatusText()
        {
            // Parse for: @, # and http://
            var sb = new System.Text.StringBuilder();
            var text = Entity.Text.Replace("\n", " "); // Some statuses contain that // TODO: Support it?
            text = System.Windows.Browser.HttpUtility.HtmlDecode(text);

            for (int i = 0; i < text.Length; i++) // Very simple parser
            {
                sb.Remove(0, sb.Length);
                var c = text[i];

                if (c == '@' || c == '#')
                {
                    while (true) // Get the whole word
                    {
                        sb.Append(c);
                        i++;
                        if (i >= text.Length)
                            break;
                        c = text[i];
                        if (!char.IsLetterOrDigit(c) && c != '_')
                        {
                            i--;
                            break;
                        }
                    }
                    if (sb.Length > 1)
                    {
                        if (sb[0] == '@')
                        {
                            Text.Add("@");
                            var username = sb.ToString(1, sb.Length - 1);
                            InsertLink("from:" + username, username);
                        }
                        else // Must be #xxx
                            InsertLink(sb.ToString());
                    }
                    else
                        Text.Add(sb.ToString());
                }
                else if (text.Substring(i).StartsWith("http://", System.StringComparison.InvariantCultureIgnoreCase))
                {
                    while (true) // Get the whole word
                    {
                        sb.Append(c);
                        i++;
                        if (i >= text.Length)
                            break;
                        c = text[i];
                        if (c == ' ')
                        {
                            i--;
                            break;
                        }
                    }
                    try
                    {
                        new System.Uri(sb.ToString()); // Verify // TODO: Handle cases like: http://www.example.com) // Detect the ending ) with no matching (
                        InsertLink(sb.ToString());
                    }
                    catch // Invalid url
                    {
                        Text.Add(sb.ToString());
                    }
                }
                else // Normal text
                {
                    while (true) // Get the whole word
                    {
                        sb.Append(c);
                        i++;
                        if (i >= text.Length)
                            break;
                        c = text[i];
                        if (c == '@' || c == '#' || text.Substring(i).StartsWith("http://", System.StringComparison.InvariantCultureIgnoreCase))
                        {
                            i--;
                            break;
                        }
                    }
                    Text.Add(sb.ToString());
                }

            }
        }
    }
}